package com.wangzhenyu.learn

import androidx.lifecycle.*
import com.wangzhenyu.common.util.log.LogUtil
import com.wangzhenyu.learn.test.net.OnSellRepository
import com.wangzhenyu.learn.test.net.OnSellResult
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {

    companion object {
        const val DEFAULT_PAGE = 1
    }

    private var mCurrentPage = DEFAULT_PAGE

    private val repository by lazy {
        OnSellRepository()
    }

    //加载状态
    private
    val _loadState = MutableLiveData<LoadState>()
    val loadState: LiveData<LoadState> by ::_loadState

    //数据列表
    private val _contentList = MutableLiveData<List<OnSellResult.MapData?>>()
    val contentList: LiveData<List<OnSellResult.MapData?>> by ::_contentList


    //是否显示RecyclerView上的那一块
    private val _supportType = MutableLiveData<ShowType>().also {
        it.value = ShowType.Yes
    }
    val supportType: LiveData<ShowType> by ::_supportType

    //ViewStub中显示的值
    private val _viewStubValue = MutableLiveData<Float>().also {
        it.value = 0.00f
    }
    val viewStubValue: LiveData<Float> by ::_viewStubValue

    fun loadData() {
        //更新状态
        _loadState.value = LoadState.LOADING
        //加载第一页数据

        loadDataByPage(mCurrentPage)

    }

    private fun loadDataByPage(page: Int) {
        viewModelScope.launch {
            try {
                val result = repository.getOnSellListByPage(page)
                //对数据进行处理
                if (result.data == null) {
                    //未拿到数据
                    _loadState.postValue(LoadState.EMPTY)
                } else {
                    _loadState.postValue(LoadState.SUCCESS)
                    _contentList.postValue(result.data.tbk_dg_optimus_material_response?.result_list?.map_data)
                }
            } catch (e: Exception) {
                _loadState.postValue(LoadState.ERROR)
                LogUtil.default01(e.message.toString())
            }
        }
    }

}

enum class LoadState {
    LOADING, SUCCESS, EMPTY, ERROR, NONE
}

enum class ShowType {
    Yes, No
}